<template>
  <div class="rightBodyContent">
    <div class="rightBodyContent-in" v-if="activeDetail">
      <div class="fooddetail">
        <el-page-header @back="goBack" content="实时详情">
        </el-page-header>
        <div class="eidtbody">
          <p class="mb-20 activetab-box">
            <!--            0离去1在线2未约3失约-->
            <span :class="tablineOption==1?'active':''" @click="tabline(1)">正常（{{ activeDetail[1] ? activeDetail[1].length : 0 }}）</span>
            <span :class="tablineOption==0?'active':''" @click="tabline(0)">离去（{{ activeDetail[0] ? activeDetail[0].length : 0 }}）</span>
            <span :class="tablineOption==3?'active':''" @click="tabline(3)">失约（{{ activeDetail[3] ? activeDetail[3].length : 0 }}）</span>
            <span :class="tablineOption==2?'active':''" @click="tabline(2)">未预约（{{ activeDetail[2] ? activeDetail[2].length : 0 }}）</span></p>
          <!--          <p class="infotop mb-10">注：本区角达标时长为 {{ pageOption ? pageOption.time : '未知' }}分钟</p>-->
          <el-button size="mini" @click="studentComment(1)" class="mb-20" type="primary">
            批量点评
          </el-button>
          <div class="fooddetail-list">
            <el-table
                ref="multipleTable"
                :data="activeDetail[tablineOption]?activeDetail[tablineOption]:[]"
                :stripe="tableoption.tableStripe"
                :border="tableoption.tableBorder"
                tooltip-effect="dark"
                style="width: 100%"
                header-cell-class-name="table-text-c"
                cell-class-name="table-text-c">
              <el-table-column
                  label="学生头像" align="center" :key="1">
                <template slot-scope="scope">
                  <div class="checkImgDialog width60 mg-auto"
                       :style="{backgroundImage:'url('+scope.row.pic+')',backgroundSize:'cover',backgroundPosition:'center'}"
                       @click="viewImgDialog(scope.$index)" v-if="scope.row.pic">
                    <div class="imgpreviewBody">
                      <div class="imgpreview">
                        <i class="el-icon-view"></i>
                      </div>
                    </div>
                  </div>
                  <div class="checkImgDialog width60 mg-auto"
                       :style="{backgroundImage:'url('+defultUser+')',backgroundSize:'cover',backgroundPosition:'center'}"
                       v-else>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                  prop="name"
                  label="学生姓名" align="center" :key="2">
              </el-table-column>
              <el-table-column
                  prop="class_name"
                  label="学生班级" align="center" :key="3">
              </el-table-column>
              <el-table-column
                  label="时长" align="center" :key="4" v-if="tablineOption!==2">
                <template slot-scope="scope">
                  {{ scope.row.time }}
                </template>
              </el-table-column>
              <el-table-column
                  label="操作"
                  width="280" align="center">
                <template slot-scope="scope">
                  <div style="display: flex" v-if="userInfomation">
                    <!--                    <el-button size="mini" @click="showlist(scope.$index)">他的预约</el-button>-->
                    <el-button type="primary" size="mini" @click="studentCornerEdit(scope.$index,1)"
                               v-if="tablineOption!==4&&tablineOption!==2&&(pageOption.class_id==userInfomation.class_id||userInfomation.id ==pageOption.user_id)">
                      实时采集
                    </el-button>
                    <el-button size="mini" @click="studentComment(2, scope.$index)"
                               v-if="tablineOption!==2&&(pageOption.class_id==userInfomation.class_id||userInfomation.id ==pageOption.user_id)">
                      评价点评
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      <!--viewImgDialog.vue-->
      <viewImgDialog :privaImgObj="imgsrcCheck" :visible.sync="dialogImgVisible"></viewImgDialog>
      <lookcorner :dishOption="dishOption" :visible.sync="cornerVisible"></lookcorner>
    </div>
  </div>
</template>

<script>
import viewImgDialog from '@/components/dialog/previewImgDialog.vue'
import lookcorner from '@/components/dialog/lookcorner.vue'
import {pagination, tableoption, yearDay} from '@/utils/util.js'
import api from '@/utils/api.js'

export default {
  components: {
    viewImgDialog,
    lookcorner
  },
  watch: {
    activeDetail() {
      console.log('数据变更', this.activeDetail)
    }
  },
  data() {
    return {
      defultUser: this.defultUser,
      currentDate: new Date(),
      tableoption: tableoption,
      editId: this.$route.query,
      arryList: {},
      dialogDrawerVisible: false,
      dishOption: null,
      dayTime: '',
      // 预览
      imgsrcCheck: '',
      dialogImgVisible: false,
      cornerVisible: false,
      tablineOption: 1,
      // activeDetail: this.global.cornerArray,
      userInfomation: null,
      pageOption: null,
      ws: {},
      activeDetail: {
        0: [],
        1: [],
        2: [],
        3: []
      } // 重组区角数据内容 0离去1在线2未约3失约
    }
  },
  created() {
    // this.global.ws.send(JSON.stringify({
    //   'facility_code': this.$route.query.facility_code,
    //   'type': 1
    // }))
    // this.global.getSocket(this.$route.query.facility_code)
    this.getSocket(this.$route.query.facility_code)
  },
  methods: {
    // 初始化
    InitFn() {
      this.$fetch(api.release_detail, {
        id: this.editId.detailData.facility.id_code
      }).then((response) => {
        if (response.code === 0) {
          for (let i in response.vo.dish) {
            let count = response.vo.dish[i].goodNum + response.vo.dish[i].notGoodNum
            let favorableRate = (response.vo.dish[i].goodNum / count).toFixed(2)
            let count_last = (favorableRate * 100).toFixed(2)
            if (count === 0) {
              count_last = 0
            }
            console.log('qq', count)
            response.vo.dish[i].favorableRate = count_last
          }
          this.dayTime = yearDay(response.vo.create_time)
          this.arryList = response.vo.dish
          console.log('list', this.arryList)
        } else {
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    tabline(option) {
      this.tablineOption = option
    },
    showlist(index) {
      this.dishOption = this.activeDetail[this.tablineOption][index]
      this.cornerVisible = true
    },
    goBack() {
      this.$router.go(-1)
    },
    viewImgDialog(index) {
      this.imgsrcCheck = [this.activeDetail[this.tablineOption][index].pic]
      this.dialogImgVisible = true
    },
    studentCornerEdit(index, type) {
      let pageOption = JSON.parse(this.editId.detailData)
      this.$router.push('/studentCornerEdit?type=' + type + '&corner_id=' + pageOption.id + '&option=' + JSON.stringify(this.activeDetail[this.tablineOption][index]))
    },
    studentComment(type, index) {
      if (type === 1) {
        this.$router.push('/commentCorner?editId=' + this.editId.detailData + '&type=' + type)
      } else {
        this.$router.push('/commentCorner?editId=' + this.editId.detailData + '&type=' + type + '&option=' + JSON.stringify(this.activeDetail[this.tablineOption][index]))
      }
    },
    numberChange(option) {
      return Number(option)
    },
    // socket对接=======================star
    getSocket(optionId) {
      let n = this;
      console.log('this.ws', this.ws, this.ws.readyState)
      if (this.ws.readyState === 1) {
        console.log('不需要去连接socket，直接发送区角mac给后台', optionId)
        this.loginsocket(optionId)
      } else {
        console.log('需要去连接socket')
        this.ws = new WebSocket('ws://' + this.$BASE_URL + ':8383')
      }

      this.ws.onmessage = function (res) {
        if (res.data === '1') {
          // console.log('登入成功进行区角推送：', res)
          n.loginsocket(optionId)
        } else {
          n.getCornerArrayFn(res.data)
          // console.log('区角动态返回的数据', res)
        }
      }
      // 成功连上了socket
      this.ws.onopen = () => {
        console.log('成功连上了socket', optionId)
      }
      this.ws.onerror = function (err) {
        console.log('失败了ws', err)
      }
      this.ws.onclose = function (err) { // 关闭 websocket
        console.log('socket已经关闭了', err)
        // console.log('连接已关闭...')
        // console.log('链接', that.$route.path)
        // if (that.$route.path !== '/') {
        //   setTimeout(() => {
        //     that.localSocket()
        //     that.ws.onopen = function () {
        //       that.ws.send(JSON.stringify({'type': 'bind_id', 'from_id': that.user_id}))
        //     }
        //   }, 2000)
        // }
      }
    },
    // 处理socket返回的数据
    getCornerArrayFn(option) {
      if (option) {
        let a = JSON.parse(option)
        let newlist = {}
        for (let i in a) {
          // 判断学生类型
          if (!newlist[a[i].type]) {
            newlist[a[i].type] = []
          }
          newlist[a[i].type].push(a[i])
          // if (this.cornerArray[a[i].type]) {
          //   // 判断学生是否存在本类型中
          //   // if (this.cornerArray[a[i].type][a[i].id]) {
          //   //
          //   // }
          //
          // }
        }
        console.log('处理实时数据内容：', newlist)
        this.activeDetail = JSON.parse(JSON.stringify(newlist))
      }
    },
    // 对socket发送区角信息
    loginsocket(optionId) {
      console.log('发送区角信息到后台')
      this.ws.send(JSON.stringify({
        'mac': optionId,
        'type': 1
      }))
    },
    // 关闭socket
    colseSocket() {
      this.ws.close()
    },
    // socket===========================end
  },
  mounted() {
  },
  // 离开页面关闭socket
  beforeRouteLeave(to, form, next) {
    console.log('页面离开关闭socket！！！进行重置')
    this.colseSocket()
    next()
  }
}
</script>
